#include "b16.h"


/* Recibe un valor de 8 bits en binario y los convierte en 2 bytes (16 bits) a hexa */
void d(unsigned char* vector,uint8_t value)
{
	const unsigned char vector_converter[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
	uint8_t aux = value << 4; // Ej: value = 11110001 -> 00010000
	uint8_t less_sing = aux >> 4;//Ej: idem value anterior 00000001=1
	uint8_t most_sing = value >> 4; // Ej: idem value anterior 00001111=15
	vector[0] = vector_converter[most_sing];//Ej: vector_converter[15]
	vector[1] = vector_converter[less_sing];//Ej:vector_converter[1]
	vector[2] = '\0';
}

void c(int infd, int outfd, uint8_t ch) {
	   unsigned char hexa[3];
	   d(&hexa[0],ch);
	   fprintf((void*)outfd, "%s", hexa);

}

void b(int infd, int outfd) {
	uint8_t ch = fgetc((void*)infd);
	if (!feof((FILE*)infd)) {
		c(infd, outfd, ch);
	}
}

void a(int infd, int outfd) {
	while(!feof((FILE*)infd)) {
		b(infd, outfd);
	}
}

int encode(int infd, int outfd) {

	a(infd, outfd);
	return 0;

}

/*Recibe un vector de dos caracteres hexa y los convierte a un caracter en binario*/
uint8_t h(unsigned char* vector)
{


	uint8_t less_bits = vector[1] - '0'; //Ej: 00001001
	uint8_t most_bits = vector[0] - '0'; //Ej: 00000001.
	if (less_bits >= 49)
		less_bits = less_bits - 39;
	else if (less_bits >= 17)
		less_bits = less_bits - 7;

	if (most_bits >= 49)
		most_bits = most_bits - 39;
	else if (most_bits >= 17)
		most_bits = most_bits - 7;

	most_bits = most_bits << 4; //Corro 4 bits a la izq: 00010000
	uint8_t total = most_bits | less_bits; //OR logico : 00011001 = 25
	return total;
}

/*Toma el archivo de entrada y mientras lo va procesando y convirtiendo a binario
 * lo va escribiendo en la salida
 */

void g(int indice_par_hexa, unsigned char* par_hexa, int outfd) {
    if (indice_par_hexa == 1)
		 {
		   	--indice_par_hexa;
		   	uint8_t valor_binario = h(par_hexa); //convierto par hexa a binario
		   	fputc(valor_binario, (FILE*)outfd); //escribo en la salida
		   }
		 else
		 {
		  	++indice_par_hexa;
		 }
}

void f(int infd, int outfd, int indice_par_hexa, unsigned char* par_hexa) {
	while(!feof((FILE*)infd))
			{
				unsigned char c = fgetc((FILE*)infd);
			    par_hexa[indice_par_hexa] = c;
			    g(indice_par_hexa, par_hexa, outfd);

			}
}

void e(int infd, int outfd, int indice_par_hexa, unsigned char* par_hexa) {
	while(indice_par_hexa < 1)
			f(infd, outfd, indice_par_hexa, par_hexa);

}

int decode(int infd, int outfd) {

	    unsigned char par_hexa[3]; //vector donde se almacenan el par hexa de dos bytes
		par_hexa[2]='\0';
		int indice_par_hexa = 0;
		e(infd, outfd, indice_par_hexa, par_hexa);


	return 0;

}



